//
//  YsSmartPenManager.m
//  YsSmartPenCoreModule
//
//  Created by Cer on 2020/4/20.
//

#import "YsSmartPenManager.h"
#import <YYKit/YYKit.h>

@interface YsSmartPenManager() <TQLPenSignal,OnBLEScanListener>
/// smartPen对象
@property (nonatomic, strong) PenCommAgent *penCommAgent;
/// 蓝牙回调的block
@property (nonatomic, copy) void (^scanResultBlock) (CBPeripheral *_Nullable peripheral,NSDictionary * _Nullable advertisementData,NSNumber * _Nullable RSSI,BOOL isTimeOut);
/// 连接状态的blcok
@property (nonatomic, copy) void (^connectResultBlock) (YsSmartPenManagerConnectStatus connectStatus);
/// 保存定时器
@property (nonatomic, strong) NSMutableDictionary *timerDic;
@end

@implementation YsSmartPenManager

static YsSmartPenManager *shareManager = nil;

+ (instancetype)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [self new];
    });
    return shareManager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _penCommAgent = [PenCommAgent getInstance];
        _penCommAgent.onBlEScanListener = self;
        _penCommAgent.pensignal = self;
    }
    return self;
}

- (void)searchSmartPenWithTimeInterval:(NSTimeInterval)seconds withScanResult:(void(^)(CBPeripheral *_Nullable peripheral,NSDictionary * _Nullable advertisementData,NSNumber * _Nullable RSSI, BOOL isTimeOut))scanResult
{
    NSParameterAssert(seconds);
    NSParameterAssert(scanResult);
    self.scanResultBlock = scanResult;

    [self closeTimer];
    [self.penCommAgent findAllDevices];
    ///
    NSTimer *timer = [NSTimer timerWithTimeInterval:seconds block:^(NSTimer * _Nonnull timer) {
        [self.penCommAgent stopFindAllDevices];
        self.scanResultBlock(nil, nil, nil, YES);
    } repeats:NO];
    [self.timerDic setValue:timer forKey: NSStringFromSelector(_cmd)];
}

- (void)stopFindDevices
{
    [self closeTimer];
}

- (void)onScanResult:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    self.scanResultBlock(peripheral, advertisementData, RSSI, NO);
}

- (void)connectSmartPenWithMacAdress:(NSString *)macAdress withTimeout:(NSTimeInterval)timeout withConnectResult:(void(^)(YsSmartPenManagerConnectStatus connectStatus))connectResult
{
    self.connectResultBlock = connectResult;
    [self searchSmartPenWithTimeInterval:timeout withScanResult:^(CBPeripheral * _Nullable peripheral, NSDictionary * _Nullable advertisementData, NSNumber * _Nullable RSSI, BOOL isTimeOut) {
        if (isTimeOut) {
            self.connectResultBlock(YsSmartPenManagerConnectTimeoutStatus);
            return;
        }
            /// 获取mac地址
        NSData *data = advertisementData[@"kCBAdvDataManufacturerData"];
        NSString *macAdress = [BLEDataTransform getNewMacAdress:data];
        if ([macAdress isEqualToString:macAdress]) {
            [self.penCommAgent stopFindAllDevices];
            [self.penCommAgent connect:peripheral];
        }
    }];
}

- (void)connectSmartPenWithPeripheral:(CBPeripheral *)peripheral
                          withTimeout:(NSTimeInterval)timeout withConnectResult:(void(^)(YsSmartPenManagerConnectStatus connectStatus))connectResult
{
    self.connectResultBlock = connectResult;
    [self.penCommAgent connect:peripheral];
}

/// 连接成功
- (void)onConnected:(int)forceMax fwVersion:(NSString *)fwVersion
{
    if (self.connectResultBlock) self.connectResultBlock(YsSmartPenManagerConnectSuccessStatus);
    [self closeTimer];
}

// 连接失败
- (void)onConnectFailed
{
    if (self.connectResultBlock) self.connectResultBlock(YsSmartPenManagerConnectFailStatus);
    [self closeTimer];
}

/// 断开连接
- (void)onDisconnected
{
    
}

- (void)requestOrTComandTimeout:(TQLComandTimeoutType)timeoutType
{
    if (timeoutType == BLE_CONNECT_TIMEOUT) {
        self.connectResultBlock(YsSmartPenManagerConnectTimeoutStatus);
    }
}

#pragma mark - helper
- (void)closeTimer
{
    NSTimer *lastTimer = [self.timerDic valueForKey:NSStringFromSelector(@selector(searchSmartPenWithTimeInterval:withScanResult:))];
    if (lastTimer) [lastTimer invalidate];
    [self.penCommAgent stopFindAllDevices];
}

#pragma mark - getter
- (NSMutableDictionary *)timerDic
{
    if (!_timerDic) {
        _timerDic = [NSMutableDictionary dictionary];
    }
    return _timerDic;
}
@end
